package com.work.daily;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 给定一个仅包含数字 2-9 的字符串，返回所有它能表示的字母组合。
 给出数字到字母的映射如下（与电话按键相同）。注意 1 不对应任何字母。
 https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/
 * Created by suk on 2020/8/26.
 */
public class D4_LetterCombinations_17_01 {
    public static void main(String[] args) {
        String digits = "234";
        D4_LetterCombinations_17_01 d4 = new D4_LetterCombinations_17_01();
        System.out.println(d4.letterCombinations(digits));
    }

    List<String> res = new ArrayList<>();
    StringBuilder temp = new StringBuilder();
    Map<Character, String> letters = new HashMap<Character, String>() {{
        put('2', "abc");
        put('3', "def");
        put('4', "ghi");
        put('5', "jkl");
        put('6', "mno");
        put('7', "pqrs");
        put('8', "tuv");
        put('9', "wxyz");
    }};

    public List<String> letterCombinations(String digits) {

        if (digits == null || digits.length() == 0)
            return res;

        dfs(digits, 0);

        return res;
    }

    public void dfs(String digits, int cur) {

        if (temp.length() == digits.length()) {
            res.add(String.valueOf(temp));
            return;
        }

        for (int i = cur; i < digits.length(); ++i) {

            for(int j = 0; j < letters.get(digits.charAt(i)).length(); ++j){

                //做选择（回溯算法基本模板三部曲，做选择--递归--撤销选择）
                temp.append(letters.get(digits.charAt(i)).charAt(j));

                //递归
                dfs(digits, i + 1);

                //撤销选择
                temp.deleteCharAt(temp.length() - 1);
            }
        }


    }


}
